<template>
  <CommonPage>
    <MyTable
      ref="$table"
      v-model:query-items="queryItems"
      :columns="columns"
      :get-data="userApi.getUserList"
      :index="true"
      list-key="/user:get"
    >
      <template #search>
        <MyTQI>
          <n-input
            v-model:value="queryItems.name"
            type="text"
            placeholder="请输入搜索姓名/账号"
            clearable
          >
            <template #suffix>
              <n-icon size="20" :component="Search"></n-icon>
            </template>
          </n-input>
        </MyTQI>
        <MyTQI>
          <AsyncSelect
            v-model:value="queryItems.roleId"
            :options="methods.getRoleOptions"
            value-key="roleId"
            label-key="name"
            placeholder="用户角色"
          />
        </MyTQI>
        <MyTQI label="创建时间" :content-width="300">
          <n-date-picker
            v-model:formatted-value="queryItems.timeLimit"
            type="daterange"
            clearable
          />
        </MyTQI>
      </template>
      <template #action>
        <n-button v-permission="`/user:post`" type="primary" @click="handleAdd">添加用户</n-button>
        <n-button
          v-permission="`mrg_user_pull`"
          type="primary"
          :loading="data.syncLoading"
          @click="methods.syncUser"
        >
          拉取用户
        </n-button>
      </template>
    </MyTable>
    <MyModal
      ref="$form"
      :model-form="model"
      :disabled="type === 'view'"
      :width="900"
      @submit="handleSubmit"
    >
      <n-form-item label="姓名" path="name" :rule="{ required: true, message: '请输入姓名' }">
        <n-input v-model:value="model.name" maxlength="30" clearable />
      </n-form-item>
      <n-form-item label="账号" path="account" :rule="{ required: true, message: '请输入账号' }">
        <n-input
          v-model:value="model.account"
          maxlength="30"
          clearable
          :disabled="type !== 'add'"
        />
      </n-form-item>
      <n-form-item
        v-if="type === 'add'"
        label="密码"
        path="password"
        :rule="{ required: true, message: '请输入密码' }"
      >
        <n-input
          v-model:value="model.password"
          type="password"
          show-password-on="click"
          maxlength="30"
          clearable
        />
      </n-form-item>
      <n-form-item
        v-if="type === 'add'"
        label="确认密码"
        path="confirmPassword"
        :rule="[
          { required: true, message: '请输入确认密码' },
          { validator: methods.validatorPassword },
        ]"
      >
        <n-input
          v-model:value="model.confirmPassword"
          type="password"
          show-password-on="click"
          maxlength="30"
          clearable
        />
      </n-form-item>
      <n-form-item label="绑定角色" path="roleId" :rule="{ required: true, message: '请输入密码' }">
        <AsyncSelect
          v-model:value="model.roleId"
          :options="methods.getRoleOptions"
          value-key="roleId"
          label-key="name"
        />
      </n-form-item>
      <n-form-item label="组别" path="deptId" :rule="{ required: true, message: '请输入组别' }">
        <AsyncSelect
          v-model:value="model.deptId"
          label-key="name"
          value-key="dept_id"
          :options="
            type !== 'add'
              ? () =>
                  taskProjectApi
                    .deptAllList()
                    .then((res) => res.data.concat([{ name: '系统管理员组', dept_id: 'od-admin' }]))
              : [
                  { name: '外包组', dept_id: 'od-outsource' },
                  { name: '系统管理员组', dept_id: 'od-admin' },
                ]
          "
          :disabled="type !== 'add'"
        />
      </n-form-item>
      <n-form-item label="附属组别" path="deptIdv2">
        <AsyncSelect
          v-model:value="model.deptIdv2"
          label-key="name"
          value-key="dept_id"
          :multiple="true"
          :options="() => taskProjectApi.deptAllList().then((res) => res.data)"
        />
      </n-form-item>
    </MyModal>
    <MyModal ref="$formReset" :model-form="modelReset" :width="900" @submit="handleSubmitReset">
      <n-form-item label="密码" path="password" :rule="{ required: true, message: '请输入密码' }">
        <n-input
          v-model:value="modelReset.password"
          type="password"
          show-password-on="click"
          maxlength="30"
          clearable
        />
      </n-form-item>
    </MyModal>
  </CommonPage>
</template>

<script setup lang="jsx">
import { usePermissionStore } from '@/store'
import * as userApi from '@/api/user'
import * as feishuApi from '@/api/feishu'
import * as taskProjectApi from '@/api/taskProject'
import { getAllRoles } from '@/api/role'
import { useCrudPro } from '@/hooks/useCrudPro'
import { Search } from '@vicons/ionicons5'
import { formatToIds, formatToSel } from '@/utils/format'
defineOptions({ name: 'UserIndex' })
const { hasPermission } = usePermissionStore()
const data = reactive({
  statusLoading: false,
  currentUser: null,
  syncLoading: false,
})
const methods = reactive({
  validatorPassword(_, value, callback) {
    if (`${value}` !== `${model.value.password}`) {
      callback(new Error('密码不一致！'))
    } else {
      callback()
    }
  },
  async setStatus({ userId }, status) {
    data.currentUser = userId
    data.statusLoading = true
    await userApi.setStatus({ userId, status })
    data.currentUser = null
    data.statusLoading = false
    $table.value.handleQuery()
  },
  getRoleOptions() {
    return getAllRoles().then((res) => res.data)
  },
  syncUser() {
    data.syncLoading = true
    feishuApi.syncUser().then(() => {
      data.syncLoading = false
      $message.success('同步成功')
      $table.value.handleSearch()
    })
  },
})
const queryItems = ref({})
const columns = [
  { key: 'name', title: '姓名' },
  { key: 'account', title: '账号' },
  { key: 'deptName', title: '组名' },
  { key: 'position', title: '岗位' },
  { key: 'roleName', title: '角色' },
  {
    key: 'status',
    title: '状态',
    render(row) {
      return (
        <n-switch
          value={row.status}
          onUpdateValue={(val) => methods.setStatus(row, val)}
          loading={data.currentUser === row.userId && data.statusLoading}
          checked-value="ENABLE"
          unchecked-value="LOCKED"
          disabled={!hasPermission('mrg_user_status')}
        >
          {{ checked: () => '启用', unchecked: () => '禁用' }}
        </n-switch>
      )
    },
  },
  { key: 'createTime', title: '创建时间', render: ({ createTime }) => $format(createTime) },
  {
    title: '操作',
    key: 'actions',
    width: 220,
    align: 'left',
    fixed: 'right',
    hideInExcel: true,
    render(row) {
      return (
        <n-flex>
          <n-button v-permission="/user:put" text onClick={() => handleEdit(row)}>
            修改
          </n-button>
          <n-button
            v-permission="/user/pass/reset:post"
            text
            onClick={() =>
              handleReset(row, () => {
                $formReset.value.setState('title', '重置密码')
              })
            }
          >
            重置密码
          </n-button>
          <n-button
            v-permission="/user:delete"
            text
            onClick={() =>
              handleDelete(row.userId, {
                title: '删除用户',
                content: `请确定是否删除用户：${row.name}`,
              })
            }
          >
            删除
          </n-button>
        </n-flex>
      )
    },
  },
]
const { type, model, $form, $table, handleAdd, handleEdit, handleSubmit, handleDelete } =
  useCrudPro({
    name: '用户',
    initForm: {
      userId: null,
      name: null,
      account: null,
      password: null,
      roleId: null,
      deptId: 'od-outsource',
      deptIdv2: null,
    },
    apis: {
      add: userApi.addUser,
      edit: userApi.editUser,
      del: userApi.deleteUser,
      info: ({ userId }) =>
        userApi.getUserInfo(userId).then((res) => {
          res.data['deptIdv2'] = formatToSel(res.data['deptIdv2'])
          return res.data
        }),
    },
    formatParams(params) {
      params.deptIdv2 = formatToIds(params.deptIdv2)
      return params
    },
  })
const {
  model: modelReset,
  $form: $formReset,
  handleEdit: handleReset,
  handleSubmit: handleSubmitReset,
} = useCrudPro({
  name: '用户',
  initForm: {
    userId: null,
    password: null,
  },
  apis: {
    edit: ({ userId, ...other }) => userApi.resetPass(userId, other),
  },
})
</script>
